package com.liferayinaction.portlet;
import java.io.IOException;
import java.util.Enumeration;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HelloYouPortlet extends GenericPortlet {
	
	private static Log _log = LogFactory.getLog(HelloYouPortlet.class);
	
	protected String editJSP;
	protected String viewJSP; 
	
	public void init() throws PortletException{
		editJSP = getInitParameter("edit-template");
		viewJSP = getInitParameter("view-template");
	}
	
	public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
		PortletPreferences prefs = renderRequest.getPreferences();
		Enumeration<String> prefNames = prefs.getNames();
		while(prefNames.hasMoreElements()){
			_log.info(prefNames.nextElement());
		}
		String userName = (String) prefs.getValue("name", "no");
		if(userName.equalsIgnoreCase("no")) {
			userName = "";
		}
		renderRequest.setAttribute("userName", userName);
		include(viewJSP, renderRequest, renderResponse);
	} 

	private void include(String path, RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
		PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);
		if(portletRequestDispatcher == null){
			_log.error(path + " is not a valid include");
		} else {
			portletRequestDispatcher.include(renderRequest, renderResponse);
		}
	}
	
	public void doEdit(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
		renderResponse.setContentType("text/html");
		PortletURL addName = renderResponse.createActionURL();
		addName.setParameter("addName", "addName");
		renderRequest.setAttribute("addNameUrl", addName.toString());
		include(editJSP, renderRequest, renderResponse);
	}
	
	public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException {
		String addName = actionRequest.getParameter("addName");
		if (addName != null) {
			PortletPreferences prefs = actionRequest.getPreferences();
			prefs.setValue("name", actionRequest.getParameter("userName"));
			prefs.store();
			actionResponse.setPortletMode(PortletMode.VIEW);
		}
	}
}
